from django.shortcuts import render, HttpResponse, redirect
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsForm, LoginForm
from django.http import JsonResponse
from utils.image_code import check_code
from io import BytesIO
from web.models import UserInfo, Transaction, PricePolicy
from django.db.models import Q
import uuid
import datetime


def register(request):
    """注册"""
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'web/register.html', {'form': form})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 通过验证,写入数据库
        # 但是数据库的写入密码必须是加密的
        # instance = models.UserInfo.objects.create(**form.cleaned_data)
        # 注册成功 用户表中新建了一条数据
        instance = form.save()  # 相当于上面的代码 但是save会剔除数据库没有字段的数据
        policy_object = PricePolicy.objects.filter(category=1, title="个人免费版").first()

        # 创建交易记录
        # 获取价格策略的方式一
        Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=policy_object,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()

        )
        return JsonResponse({'status': True, 'data': '/login/sms/'})
    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """ 发送短信 """
    # 1.通过request.GET方式拿到前端的值再验证
    # mobile_phone = request.GET.get("mobile_phone")
    # tpl = request.GET.get("tp")
    # # 在次验证上面的数据
    # 2.通过form组件验证
    # ①通过下面代码可以将request.GET中的参数传到account.py的SendSmsForm()函数中
    form = SendSmsForm(request, data=request.GET)
    # 只是校验手机号：不能为空、格式是否正确
    if form.is_valid():
        # 只验证手机号是否为空、格式是否正确
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    '''短信登录'''
    if request.method == 'GET':
        form = LoginSmsForm()
        return render(request, 'web/login_sms.html', {'form': form})
    form = LoginSmsForm()
    if form.is_valid():
        # 登陆成功
        mobile_phone = form.cleaned_data['mobile_phone']

        # 把用户名写在session中
        user_object = UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        request.session['user_id'] = user_object.id
        request.session.set_expiry(60 * 60 * 24 * 14)

        return JsonResponse({'status': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    """用户名密码登录"""
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'web/login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user_object = UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()

        # user_object = UserInfo.objects.filter(username=username, password=password).first()
        if user_object:
            # 登录成功
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('index')
        form.add_error('username', '用户名密码错误')
    return render(request, 'web/login.html', {'form': form})


def image_code(request):
    """生成图片验证码"""

    image_object, code = check_code()

    # 保存进session中
    request.session['image_code'] = code
    # 修改过期时间
    request.session.set_expiry(60)

    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def logout(request):
    """退出"""
    request.session.flush()  # flush是清除session信息
    return redirect('index')
